/**
 * 
 */
package com.live.activity;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextPaint;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.live.common.Constant;
import com.live.common.LiveImageHelper;
import com.live.entity.User;
import com.live.task.LiveUser;
import com.live.tools.LiveTools;

/**
 * @author nhn
 * 
 */
public class LiveBaseActivity extends Activity {

	public Context context;

	public static List<Activity> activityList = new ArrayList<Activity>();

	public static List<Map<String, Object>> liveMatchList = null;

	public SharedPreferences store = null;

	// 0:未登录 1:登录
	public int userStatus = Constant.LOGOUT;

	private Dialog registDialog;

	private Dialog settingDialog;

	private Dialog loginDialog;

	private String userSex = null;

	private RadioGroup userSexGroup = null;

	private RadioButton man = null;

	private RadioButton woman = null;

	private User user = new User();

	public boolean netIsOk = true;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		context = this;

		activityList.add(this);

		// 隐藏标题
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		// 网络连接判断
		if (!LiveTools.isConnect(context)) {
			netIsOk = false;
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setCancelable(false);
			builder.setTitle("请检查网络是否正确连接！");
			builder.setIcon(android.R.drawable.ic_dialog_info);
			builder.setPositiveButton("退出程序", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					userExit();
				}
			});
			builder.create().show();
		}

		// 用户登录判断
		store = getSharedPreferences(Constant.PREFS_NAME, 0);
		if (store.getString("userId", null) != null) {
			userStatus = Constant.LOGIN;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			int maxWidth = 240;
			int maxHeight = 240;
			Uri uri = data.getData();
			try {
				Bitmap bitmap = LiveTools.uriToBitmap(uri, context);

				// 同比例压缩图片
				int originWidth = bitmap.getWidth();
				int originHeight = bitmap.getHeight();

				if (originWidth > maxWidth || originHeight > maxHeight) {

					int width = originWidth;
					int height = originHeight;

					// 若图片过宽, 则保持长宽比缩放图片
					if (originWidth > maxWidth) {
						width = maxWidth;
						double i = originWidth * 1.0 / maxWidth;
						height = (int) Math.floor(originHeight / i);
						bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
					}

					// 若图片过长, 则从上端截取
					if (height > maxHeight) {
						height = maxHeight;
						bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
					}
				}

				// 保存临时文件
				LiveImageHelper.saveImage(bitmap, "tmp");
				ImageView imageView = (ImageView) settingDialog.findViewById(R.id.userPic);

				// 将Bitmap设定到ImageView
				imageView.setImageBitmap(bitmap);

				// 设定用户头像
				user.setUserPicBitmap(bitmap);
			} catch (FileNotFoundException e) {
				Log.e("Exception", e.getMessage(), e);
			} catch (IOException e) {
				Log.e("Exception", e.getMessage(), e);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onConfigurationChanged(Configuration config) {
		super.onConfigurationChanged(config);
	}

	// 生成菜单
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.user_menu, menu);
		return true;
	}

	// 初始化菜单
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

		switch (userStatus) {
		case Constant.LOGIN:
			menu.getItem(2).setIcon(R.drawable.menu_user_off);
			menu.getItem(2).setTitle("注销");
			break;
		case Constant.LOGOUT:
			menu.getItem(2).setIcon(R.drawable.menu_user_login);
			menu.getItem(2).setTitle("登录");
			break;
		}

		return true;
	}

	// 菜单事件响应
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.userLogin:
			if (userStatus == Constant.LOGOUT) {

				// 登录
				userLogin();
			} else {

				// 注销
				userOff();
			}
			break;
		case R.id.userSetting:

			// 用户设置
			userSetting();
			break;
		case R.id.userHelp:

			// 帮助
			userHelp();
			break;
		case R.id.userRegsit:

			// 注册
			userRegist();

			break;

		case R.id.userExit:

			// 退出应用
			userExit();
			break;
		}
		return false;
	}

	// 退出应用
	public void userExit() {
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		if (Float.valueOf(Build.VERSION.RELEASE.substring(0, 3)) <= 2.1) {
			// Android2.1及以下版本退出
			activityManager.restartPackage(Constant.PREFS_NAME);
		} else {
			// Android2.2及以上版本退出
			for (int i = 0; i < activityList.size(); i++) {
				if (null != activityList.get(i)) {
					activityList.get(i).finish();
				}
			}
			activityManager.restartPackage(Constant.PREFS_NAME);
			System.exit(0);
		}
	}

	// 用户帮助
	public void userHelp() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("比分直播  " + Constant.UPGRADE_VERSION);
		String msg = "更为及时准确的体育赛事结果\n" + "更为详尽的体育赛事比分直播\n" + "比分信息来自新浪直播（http://match.sports.sina.com.cn/livecast/）\n"
				+ "                                      绿豆粥";
		builder.setMessage(msg);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		builder.setNegativeButton("使用交流", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try {
					Uri uri = Uri.parse(Constant.HOME_URL);
					Intent intent = new Intent(Intent.ACTION_VIEW, uri);
					context.startActivity(intent);
				} catch (Exception e) {
					e.printStackTrace();
				}
				dialog.cancel();
			}
		});
		builder.create().show();
	}

	// 用户注销
	public void userOff() {
		// 用户注销
		SharedPreferences userInfo = getSharedPreferences(Constant.PREFS_NAME, 0);
		SharedPreferences.Editor editor = userInfo.edit();
		editor.clear();
		editor.commit();

		// 提示注销成功
		Toast.makeText(this, "用户已注销！", Toast.LENGTH_LONG).show();

		// 页面跳转到首页
		Intent intent = new Intent();
		intent.setClass(LiveBaseActivity.this, LiveMatchActivity.class);
		startActivity(intent);
	}

	// 用户设置
	public void userSetting() {
		settingDialog = new Dialog(context);
		// 去掉标题
		settingDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		settingDialog.setContentView(R.layout.user_setting);
		// 为获取屏幕宽、高
		Display d = getWindowManager().getDefaultDisplay();
		// 获取对话框当前的参数值
		LayoutParams p = settingDialog.getWindow().getAttributes();
		// 宽度设置为屏幕的0.95
		p.width = (int) (d.getWidth() * 0.95);
		// 设置生效
		settingDialog.getWindow().setAttributes(p);
		// 显示对话框
		settingDialog.show();

		LinearLayout userInfo = (LinearLayout) settingDialog.findViewById(R.id.userInfo);

		// 用户登录后可以进行用户设置
		if (userStatus == Constant.LOGIN) {

			store = getSharedPreferences(Constant.PREFS_NAME, 0);

			// 设置帐号
			TextView userId = (TextView) settingDialog.findViewById(R.id.userId);
			userId.setText(store.getString("userId", null));
			// 设置粗体
			TextPaint userIdTP = userId.getPaint();
			userIdTP.setFakeBoldText(true);

			// 设置头像
			ImageView userPic = (ImageView) settingDialog.findViewById(R.id.userPic);

			if (Constant.Y.equals(store.getString("userPic", null))) {
				LiveImageHelper.loadBitMap(userPic, store.getString("id", null));
			}
			userPic.setOnClickListener(new ImageView.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					/* 开启Pictures画面Type设定为image */
					intent.setType("image/*");
					/* 使用Intent.ACTION_GET_CONTENT这个Action */
					intent.setAction(Intent.ACTION_GET_CONTENT);
					/* 取得相片后返回本画面 */
					startActivityForResult(intent, 1);
				}
			});

			// 设置性别
			RadioButton man = (RadioButton) settingDialog.findViewById(R.id.man);
			RadioButton woman = (RadioButton) settingDialog.findViewById(R.id.woman);
			if (Constant.USER_SEX_MAN.equals(store.getString("userSex", null))) {
				man.setChecked(true);
				woman.setChecked(false);
			} else {
				man.setChecked(false);
				woman.setChecked(true);
			}
		} else {
			// 不加载用户信息界面
			userInfo.removeAllViews();
		}

		// 保存设置按钮
		Button saveBtn = (Button) settingDialog.findViewById(R.id.saveBtn);
		saveBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				// 取得用户ID
				TextView userId = (TextView) settingDialog.findViewById(R.id.userId);

				// 取得用户性别
				String userSex = Constant.USER_SEX_MAN;
				RadioButton userSexWoman = (RadioButton) settingDialog.findViewById(R.id.woman);
				if (userSexWoman.isChecked()) {
					userSex = Constant.USER_SEX_WOMAN;
				}

				// 取得用户密码
				EditText userPwd = (EditText) settingDialog.findViewById(R.id.userPwd);
				EditText userPwdRp = (EditText) settingDialog.findViewById(R.id.userPwdRp);

				// 用户密码校验
				if (!userPwd.getText().toString().equals(userPwdRp.getText().toString())) {
					Toast.makeText(v.getContext(), "两次输入的密码不同，请重新输入！", Toast.LENGTH_LONG).show();
					return;
				}

				String url = Constant.SITE_URL + "live_user.php?";
				url += "id=" + store.getString("id", null) + "&userId=" + userId.getText().toString() + "&userPwd="
						+ userPwd.getText().toString() + "&userSex=" + userSex + "&type=e";

				user.setId(store.getString("id", null));
				user.setUserId(userId.getText().toString());
				user.setUserPwd(userPwd.getText().toString());
				user.setUserSex(userSex);
				user.setUserType("1");

				LiveUser task = new LiveUser(context, url, "编辑", settingDialog);
				task.execute(user);
			}
		});

		// 取消设置按钮
		Button cancelBtn = (Button) settingDialog.findViewById(R.id.cancelBtn);
		cancelBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				settingDialog.dismiss();
			}
		});

		// 清除缓存按钮
		Button clearBtn = (Button) settingDialog.findViewById(R.id.clearBtn);
		clearBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				LiveTools.deleteFile(context);
				Toast.makeText(v.getContext(), "缓存数据清除完毕！", Toast.LENGTH_LONG).show();
				settingDialog.dismiss();
			}
		});
	}

	// 用户注册
	public void userRegist() {
		registDialog = new Dialog(context);
		// 去掉标题
		registDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		registDialog.setContentView(R.layout.user_regist);

		// 为获取屏幕宽、高
		Display d = getWindowManager().getDefaultDisplay();
		// 获取对话框当前的参数值
		LayoutParams p = registDialog.getWindow().getAttributes();
		// 高度设置为屏幕的0.6
		// p.height = (int)(d.getHeight() * 0.6);
		// 宽度设置为屏幕的0.95
		p.width = (int) (d.getWidth() * 0.95);
		// 设置生效
		registDialog.getWindow().setAttributes(p);
		// 显示对话框
		registDialog.show();

		// 用户注册按钮
		Button registBtn = (Button) registDialog.findViewById(R.id.registBtn);

		registBtn.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				EditText userId = (EditText) registDialog.findViewById(R.id.userId);
				EditText userPwd = (EditText) registDialog.findViewById(R.id.userPwd);
				EditText userPwdRp = (EditText) registDialog.findViewById(R.id.userPwdRp);

				// 用户注册数据合法性验证
				if (!userValidate(v, userId, userPwd, userPwdRp)) {
					return;
				}

				userSexGroup = (RadioGroup) registDialog.findViewById(R.id.userSex);
				man = (RadioButton) registDialog.findViewById(R.id.man);
				woman = (RadioButton) registDialog.findViewById(R.id.woman);

				userSexGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {

						if (checkedId == man.getId()) {
							userSex = "男";
						} else if (checkedId == woman.getId()) {
							userSex = "女";
						}
					}
				});

				String url = Constant.SITE_URL + "live_user.php?";
				url += "userId=" + userId.getText().toString() + "&userPwd=" + userPwd.getText().toString()
						+ "&userPwdRp=" + userPwdRp.getText().toString() + "&userSex=" + userSex + "&type=r";

				user.setUserId(userId.getText().toString());
				user.setUserPwd(userPwd.getText().toString());
				user.setUserSex(userSex);
				user.setUserType("1");

				LiveUser task = new LiveUser(context, url, "注册", registDialog);
				task.execute(user);
			}
		});

		// 注册取消按钮
		Button cancelBtn = (Button) registDialog.findViewById(R.id.cancelBtn);
		cancelBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				registDialog.dismiss();
			}
		});

	}

	// 用户登录
	public void userLogin() {
		loginDialog = new Dialog(context);
		// 去掉标题
		loginDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		loginDialog.setContentView(R.layout.user_login);

		WindowManager m = getWindowManager();
		// 为获取屏幕宽、高
		Display d = m.getDefaultDisplay();
		// 获取对话框当前的参数值
		LayoutParams p = loginDialog.getWindow().getAttributes();
		// 高度设置为屏幕的0.6
		// p.height = (int)(d.getHeight() * 0.6);
		// 宽度设置为屏幕的0.95
		p.width = (int) (d.getWidth() * 0.95);
		// 设置生效
		loginDialog.getWindow().setAttributes(p);

		loginDialog.show();

		// 用户登录按钮
		Button loginBtn = (Button) loginDialog.findViewById(R.id.loginBtn);
		loginBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				// 登录
				EditText userId = (EditText) loginDialog.findViewById(R.id.userId);
				EditText userPwd = (EditText) loginDialog.findViewById(R.id.userPwd);

				String url = Constant.SITE_URL + "live_user.php?";
				url += "userId=" + userId.getText().toString() + "&userPwd=" + userPwd.getText().toString() + "&type=l";

				user.setUserId(userId.getText().toString());
				user.setUserPwd(userPwd.getText().toString());

				LiveUser task = new LiveUser(context, url, "登录", loginDialog);
				task.execute(user);
			}
		});

		// 登录取消按钮
		Button cancelBtn = (Button) loginDialog.findViewById(R.id.cancelBtn);
		cancelBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				loginDialog.dismiss();
			}
		});
	}

	/**
	 * 用户注册数据合法性验证
	 * 
	 * @param v
	 * @param userId
	 * @param userPwd
	 * @param userPwdRp
	 * @return
	 */
	private boolean userValidate(View v, EditText userId, EditText userPwd, EditText userPwdRp) {
		if ("".equals(userId.getText().toString())) {
			Toast.makeText(v.getContext(), "请输入用户名！", Toast.LENGTH_LONG).show();
			return false;
		}
		if (userId.getText().toString().length() > 16) {
			Toast.makeText(v.getContext(), "用户名长度请小于16位！", Toast.LENGTH_LONG).show();
			return false;
		}
		if ("".equals(userPwd.getText().toString())) {
			Toast.makeText(v.getContext(), "请输入密码！", Toast.LENGTH_LONG).show();
			return false;
		}
		if ("".equals(userPwdRp.getText().toString())) {
			Toast.makeText(v.getContext(), "请再次输入密码！", Toast.LENGTH_LONG).show();
			return false;
		}
		if (!userPwdRp.getText().toString().equals(userPwd.getText().toString())) {
			Toast.makeText(v.getContext(), "两次输入的密码不同，请重新输入！", Toast.LENGTH_LONG).show();
			return false;
		}
		if (userPwd.getText().toString().length() > 16) {
			Toast.makeText(v.getContext(), "密码长度请小于16位！", Toast.LENGTH_LONG).show();
			return false;
		}
		return true;
	}
}
